package com.xuan.mail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.mail.domin.Attachment;
import com.xuan.mail.domin.Contact;
import com.xuan.mail.service.AttachmentService;
import com.xuan.mail.mapper.AttachmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

/**
* @author 86156
* @description 针对表【attachment】的数据库操作Service实现
* @createDate 2024-03-15 14:20:38
*/
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment>
    implements AttachmentService{
    @Value("${file.upload.dir}")
    private String uploadDir;
    @Autowired
    AttachmentMapper attachmentMapper;
    @Autowired
    private ResourceLoader resourceLoader;


    @Override
    public Attachment upload(Integer emailId,MultipartFile file) throws IOException{
        String fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename();
        File filePath = new File(uploadDir + File.separator + fileName);
        System.out.println("--------------------------------------------------------------\n");
        System.out.println("filePath:"+filePath.toString());
        System.out.println("file.getContentType():"+file.getContentType());
        System.out.println("Size:"+file.getSize());
        file.transferTo(filePath);
        Attachment attachment = new Attachment();
        attachment.setIsdeleted(0);
        attachment.setFileName(fileName);
        attachment.setStoragePath(filePath.toString());
        attachment.setFileType(file.getContentType());
        attachment.setFileSize((int)file.getSize());
        attachment.setEmailId(emailId);

        // 调用Mapper保存文件信息到数据库
        attachmentMapper.insert(attachment);
        return attachment;


    }
    private String getContentType(Resource resource) {
        String contentType = null;
        String filename = resource.getFilename();
        String extension = filename.substring(filename.lastIndexOf(".") + 1);

        switch (extension) {
            case "txt":
                contentType = "text/plain";
                break;
            case "jpg":
                contentType = "image/jpeg";
                break;
            // 其他文件类型...
            default:
                contentType = "application/octet-stream";
        }
        return contentType;
    }

    @Override
    public void download(Integer attachmentId, HttpServletResponse response)throws IOException{

        Attachment attachment = attachmentMapper.selectById(attachmentId);

        Resource resource = resourceLoader.getResource("file:" + attachment.getStoragePath());

        if (attachment == null) {
            throw new RuntimeException("文件不存在");
        }

        File file = new File(attachment.getStoragePath());
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        response.setContentType(attachment.getFileType());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + attachment.getFileName() + "\"");
        try (InputStream inputStream = resource.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }



    }

    @Override
    public List<Attachment> list(Integer emailId) {

        // 调用Mapper根据emailId查询文件列表

        // 返回文件列表

        return attachmentMapper.selectList(new LambdaQueryWrapper<Attachment>()
                .eq(Attachment::getEmailId, emailId)
                .eq(Attachment::getIsdeleted, 0)
        );

    }

    @Override
    public void delete(Integer id) {

        // 调用Mapper删除文件信息
        Attachment attachment = attachmentMapper.selectById(id);
        if (attachment == null) {
            throw new RuntimeException("文件不存在");
        }
        attachment.setIsdeleted(1);
        attachmentMapper.updateById(attachment);

    }



}




